from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import index_blue
from info import redis_store
import logging
from flask import current_app, render_template, session, request, jsonify, g
from info.models import User, News,Category

# 首页新闻列表
# 请求路径: /newslist
# 请求方式: GET
# 请求参数: cid,page,per_page
# 返回值: data数据
@index_blue.route('/newslist')
@user_login_data
def newslist():
    #1, 获取参数
    cid = request.args.get("cid","1")
    page = request.args.get("page","1")
    per_page = request.args.get("per_page","5")

    #2, 参数类型转换(整数),方便做分页查询
    try:
        page =  int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 5

    #3, 分页查询数据,组织数据
    try:

        #3,1 判断是否是cid==1, 如果是1表示获取最新新闻, 按照时间倒序排列就是最新新闻
        condition = [News.status == 0]

        if cid != "1":
            condition.append(News.category_id == cid)

        paginate = News.query.filter(*condition).order_by(News.create_time.desc()).paginate(page, per_page,
                                                                                                       False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")

    totalPage = paginate.pages # 共有多少页
    items = paginate.items #当前页数的所有对象
    currentPage = paginate.page #当前页

    #3,1 将对象列表转成字典列表
    newList = []
    for news in items:
        newList.append(news.to_dict())

    #4,返回响应,携带数
    return jsonify(errno=RET.OK,errmsg="获取成功",totalPage=totalPage,currentPage=currentPage,newsList=newList)


@index_blue.route('/',methods=["GET","POST"])
@user_login_data
def show_index():

    # #1,获取session用户编号
    # user_id = session.get("user_id")
    #
    # #2,根据用户编号获取对象
    # user = None
    # if user_id:
    #     user = User.query.get(user_id)

    #3,按照点击量,查询前10条新闻
    try:
        news_list = News.query.order_by(News.clicks).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)

    #4,将新闻对象列表, 转成新闻的字典列表
    click_news_list = []
    for news in news_list:
        click_news_list.append(news.to_dict())

    #5,查询所有的分类,转成字典列表
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    category_list = []

    for category in categories:
        category_list.append(category.to_dict())

    #携带数据,渲染页面
    dict_data = {
        "user_info":g.user.to_dict() if g.user else "",
        "click_news_list":click_news_list,
        "categories":category_list
    }
    return render_template('news/index.html',data=dict_data)

#处理网站logo
@index_blue.route('/favicon.ico')
def get_logo():
    response =  current_app.send_static_file("news/favicon.ico")
    return response

#处理404页面的
@index_blue.route('/404')
@user_login_data
def page_not_found():
    data = {
        "user_info":g.user.to_dict() if g.user else ""
    }
    return render_template('news/404.html',data=data)